<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <select name="" id="category">

    </select>
    <select name="" id="child"></select>
    <script>

        // id作为value值，name作为text
        let data = [

            {
                id: 1,
                name: '蔬菜',
                child: [{
                    id: '1',
                    name: '白菜'
                }, {
                    id: '2',
                    name: '萝卜'
                }, {
                    id: '3',
                    name: '菠菜'
                }]
            },
            {
                id: 2,
                name: '肉类',
                child: [{
                    id: '1',
                    name: '猪肉'
                }, {
                    id: '2',
                    name: '羊肉'
                }, {
                    id: '3',
                    name: '牛肉'
                }]
            },
            {
                id: 3,
                name: '蛋类',
                child: [{
                    id: '1',
                    name: '鸡蛋'
                }, {
                    id: '2',
                    name: '鹅蛋'
                }, {
                    id: '3',
                    name: '鸭蛋'
                }]
            }
        ]
        /*
        动态创建categoryde option  <option value="1">蔬菜</option>
        category 绑定onchange事件 找到选中的option.text。然后找到对应child的所有数据
        
        */
        let category = document.getElementById('category')
        let child = document.getElementById('child')

        // 动态创建categoryde option  <option value="1">蔬菜</option>
        let fn = ({ id, name } = {}) => `<option value=${id}>${name}</option>`
        // element ==>object
        let categoryHtmlStr = ''
        data.forEach(element => categoryHtmlStr += fn(element))
        category.innerHTML = categoryHtmlStr
        categoryHtmlStr = null

        let initChild = function () {
            let selectValue = this.value  //string 
            let selectedChild = data.find(element => element.id === parseInt(selectValue)).child
            //  selectedChild数据创建child option
            let childHtmlStr = ''
            selectedChild.forEach(element => childHtmlStr += fn(element))
            child.innerHTML = childHtmlStr
            childHtmlStr = null
        }
        // 初始化child select
        initChild.call(category)
        // category 绑定onchange事件 找到选中的option。然后找到对应child的所有数据
        category.onchange = function () {
            initChild.call(this)
        }






    </script>
</body>

</html>